package com.jyy.prefabricated.service;

import com.alibaba.fastjson.JSON;
import com.jyy.prefabricated.dto.AnswerDto;
import com.jyy.prefabricated.entity.Option;
import com.jyy.prefabricated.entity.Question;
import com.jyy.prefabricated.entity.StudentExerciseQuestion;
import com.jyy.prefabricated.enums.QuestionTypeEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.mapper.OptionMapper;
import com.jyy.prefabricated.mapper.QuestionMapper;
import com.jyy.prefabricated.mapper.StudentExerciseMapper;
import com.jyy.prefabricated.mapper.StudentExerciseQuestionMapper;
import com.jyy.prefabricated.vo.ExerciseQuestionOptionVo;
import com.jyy.prefabricated.vo.StudentExercisePaperVo;
import com.jyy.prefabricated.vo.StudentExerciseQuestionVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @version 1.0.0
 * @author: zjj
 */

@Service
public class StudentExerciseQuestionService {

    @Autowired
    private StudentExerciseQuestionMapper studentExerciseQuestionMapper;

    @Autowired
    private StudentExerciseMapper studentExerciseMapper;

    @Autowired
    private OptionMapper optionMapper;

    @Resource
    private QuestionMapper questionMapper;

    /**
     * 新增
     *
     * @param studentExerciseQuestion
     * @return
     */
    public Integer insert(StudentExerciseQuestion studentExerciseQuestion) {
        studentExerciseQuestionMapper.insert(studentExerciseQuestion);
        return studentExerciseQuestion.getId();
    }

    /**
     * 更新
     *
     * @param studentExerciseQuestion
     * @return
     */
    public int update(StudentExerciseQuestion studentExerciseQuestion) {
        if (studentExerciseQuestion.getId() == null) {
            throw new CustomException("参数id不能为空");
        }
        return studentExerciseQuestionMapper.updateByPrimaryKeySelective(studentExerciseQuestion);
    }

    /**
     * 回答答案
     *
     * @param dto
     * @return
     */
    public StudentExercisePaperVo answer(AnswerDto dto) {
        StudentExerciseQuestion studentExerciseQuestion = studentExerciseQuestionMapper.selectByPrimaryKey(dto.getId());
        if (StringUtils.isNotBlank(dto.getAnswer()) && StringUtils.isBlank(studentExerciseQuestion.getAnswer())) {
            //当提交答案不为空并且此题还未作答时时去保存答案
            studentExerciseQuestion.setAnswer(dto.getAnswer());
            List<Option> options = optionMapper.selectByQuestionId(studentExerciseQuestion.getQuestionId());
            //筛选出正确答案的选项数组
            List<Integer> ids = options.stream().filter(e -> e.getIfAnswer() != null && e.getIfAnswer()).map(e -> e.getId()).collect(Collectors.toList());
            List<Integer> submitAnswers = JSON.parseArray(dto.getAnswer(), Integer.class);
            Boolean ifRight = true;
            for (Integer optionId : ids) {
                if (!submitAnswers.contains(optionId) || submitAnswers.size() != ids.size()) {
                    ifRight = false;
                }
            }

            Question qe = questionMapper.selectByPrimaryKey(studentExerciseQuestion.getQuestionId());
            if (qe.getQuestionType().equals(QuestionTypeEnum.JUDGE.getValue())) {
                if (qe.getJudgmentAnswer() && submitAnswers.contains(1)) {
                    ifRight = true;

                } else if (qe.getJudgmentAnswer() == false && submitAnswers.contains(2)) {
                    ifRight = true;

                } else {
                    ifRight = false;
                }

            }

            studentExerciseQuestion.setIfRight(ifRight);
            update(studentExerciseQuestion);
        }
        return fetchQuestionsByStudentExerciseId(studentExerciseQuestion.getStudentExerciseId());
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public int delete(Integer id) {
        return studentExerciseQuestionMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public StudentExerciseQuestion selectById(Integer id) {
        return studentExerciseQuestionMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据学员练习id获取学员练习题卷
     *
     * @param studentExerciseId
     * @return
     */
    public StudentExercisePaperVo fetchQuestionsByStudentExerciseId(Integer studentExerciseId) {
        StudentExercisePaperVo paperVo = studentExerciseMapper.selectByStudentExerciseId(studentExerciseId);
        List<StudentExerciseQuestionVo> questions = studentExerciseQuestionMapper.selectQuestionVoByStudentExerciseId(studentExerciseId);
        paperVo.setQuestionCount(questions.size());
        paperVo.setQuestions(questions);
        return paperVo;
    }

    /**
     * 根据学员练习id获取学员练习题卷（包含正确答案）
     *
     * @param studentExerciseId
     * @return
     */
    public StudentExercisePaperVo fetchQuestionsByStudentExerciseIdAnswer(Integer studentExerciseId) {
        StudentExercisePaperVo paperVo = studentExerciseMapper.selectByStudentExerciseId(studentExerciseId);
        List<StudentExerciseQuestionVo> questions = studentExerciseQuestionMapper.selectQuestionVoByStudentExerciseId(studentExerciseId);

        for (StudentExerciseQuestionVo question : questions) {
            if (question.getQuestionType().equals(QuestionTypeEnum.SINGLE.getValue()) || question.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())) {
                if (question.getAnswer() == null) {
                    question.setStudentAnswer("未答题");
                } else {
                    String ans = "";
                    List<Integer> submitAnswers = JSON.parseArray(question.getAnswer(), Integer.class);

                    for (int i = 0; i < submitAnswers.size(); i++) {
                        char emumOption = 'A';
                        for (ExerciseQuestionOptionVo option : question.getOptions()) {
                            if (option.getId().equals(submitAnswers.get(i))) {
                                ans += emumOption;
                                break;
                            }
                            emumOption = (char) (emumOption + 1);
                        }
                    }
                    question.setStudentAnswer(ans);
                }
                String standardAnswer = "";
                char emumOption = 'A';
                for (ExerciseQuestionOptionVo option : question.getOptions()) {
                    if (option.getIfAnswer()) {
                        standardAnswer += emumOption;
                    }
                    emumOption = (char) (emumOption + 1);
                }
                question.setStandardAnswer(standardAnswer);

            }
            //判断题
            else if (question.getQuestionType().equals(QuestionTypeEnum.JUDGE.getValue())) {

                List<Integer> submitAnswers = JSON.parseArray(question.getAnswer(), Integer.class);
                if (submitAnswers == null || submitAnswers.size() == 0) {
                    question.setStudentAnswer("未答题");
                } else if (submitAnswers.get(0) == 1) {
                    question.setStudentAnswer("1");
                } else {
                    question.setStudentAnswer("2");
                }
                Question qe = questionMapper.selectByPrimaryKey(question.getQuestionId());
                if (qe.getJudgmentAnswer()) {
                    question.setStandardAnswer("1");

                } else {
                    question.setStandardAnswer("2");

                }
            }


        }
        paperVo.setQuestionCount(questions.size());
        paperVo.setQuestions(questions);
        return paperVo;
    }
}
